﻿using AutoMapper;

using BCVP.Net8.Common;
using BCVP.Net8.IService;
using BCVP.Net8.Model.ViwModels;
using BCVP.Net8.Repository;
using BCVP.Net8.Repository.Base;

using Newtonsoft.Json;

using SqlSugar;

using System.Linq.Expressions;

namespace BCVP.Net8.Service
{
    /// <summary>
    /// 基服务接口实现
    /// </summary>
    public class BaseService<TEntity, TEntityVM> : IBaseService<TEntity, TEntityVM> where TEntity : class, new()
    {
        private readonly IBaseRepository<TEntity> _baseRepository;
        private readonly IMapper _mapper;

        public BaseService(IBaseRepository<TEntity> baseRepository,IMapper mapper)
        {
            _mapper = mapper;
            _baseRepository = baseRepository;
        }

        public ISqlSugarClient Db => _baseRepository.Db;

        public async Task<TEntityVM> Add(TEntityVM model)
        {
            var entity = _mapper.Map<TEntity>(model);
            var entityVM = await _baseRepository.Add(entity);
            return _mapper.Map<TEntityVM>(entityVM); ;
        }

        //[UseTran(Propagation = Propagation.Required)]
        //不建议这么写，属于过度设计
        public async Task<TEntity> Add(TEntity model)
        {
            return await _baseRepository.Add(model);
        }

        public async Task<bool> DeleteById(object id)
        {
            return await _baseRepository.DeleteById(id);
        }

        public async Task<List<TEntityVM>> QueryAll()
        {
            var entities = await _baseRepository.QueryAll();
            Console.WriteLine("_baseRepository的实例HashCode值是："+_baseRepository.GetHashCode());
            var list = _mapper.Map<List<TEntityVM>>(entities);
            return list;
        }

        public async Task<TEntityVM> QueryById(object objId)
        {
            var entity =  await _baseRepository.QueryById(objId);
            return _mapper.Map<TEntityVM>(entity);
        }

        public async Task<bool> Update(TEntityVM model)
        {
            var entity = _mapper.Map<TEntity>(model);
            return await _baseRepository.Update(entity);
        }

        /// <summary>
        /// 分表查询
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="orderByFields">排序字段，如name asc,age desc</param>
        /// <returns></returns>
        public async Task<List<TEntity>> QuerySplit(Expression<Func<TEntity, bool>> whereExpression, string orderByFields = null)
        {
            return await _baseRepository.QuerySplit(whereExpression, orderByFields);
        }

        /// <summary>
        /// 分表写入实体数据
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns></returns>
        public async Task<List<long>> AddSplit(TEntity entity)
        {
            //插入并返回雪花ID并且自动赋值ID　
            return await _baseRepository.AddSplit(entity);
        }
    }
}
